package Util;


import java.awt.*;
import java.awt.event.InputEvent;
import java.util.HashMap;

public abstract class AbstractClickNumber {

    private static HashMap<Character, Point> clickNumbers;


    protected abstract HashMap<Character, Point> getTureMap();

    public void doClickNumber(Integer nums) throws InterruptedException {
        if(clickNumbers == null) {
            clickNumbers = getTureMap();
        }
//        click(lastNums);
        clickTwo(nums);
    }

    public void doClickNumber(Integer nums, Integer over) throws InterruptedException {
        clickNumbers = getTureMap();
//        click(lastNums, over);
        clickTwo(nums);
    }

    private void clickTwo(Integer nums) throws InterruptedException {
        String clickNumbers = String.format("%04d", nums).substring(0, 4);
        System.err.println("这次尝试的密码是：" + clickNumbers);
        Thread.sleep(500);
        castAndClick(clickNumbers);
    }

    private void click(Integer lastNums, Integer over) {
        for (Integer i = lastNums; i < over; i++) {
            String clickNumbers = String.format("%04d", i).substring(0, 4);
            castAndClick(clickNumbers);
        }
    }

    private void castAndClick(String clickNumbers) {
        try {
            Robot robot = new Robot();
            for (int i = 0; i < 4; i++ ) {
                char c = clickNumbers.charAt(i);
                Point point = AbstractClickNumber.clickNumbers.get(c);
                if(point != null) {
/*                    Thread.sleep(1000);
                    //睡会等日志*/
                    System.out.println("点击数字：" + c + ", 位置：" +  point);
                    robot.mouseMove(point.x, point.y);

                    //clickAndUnClick
                    robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
                    robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

                    //200ms delay
                    robot.delay(500);
                } else {
                    System.err.println("按键错误");
                }
            }
            Thread.sleep(1500);
        } catch (AWTException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private void click(Integer lastNums) {
        for (Integer i = lastNums; i < 10000; i++) {
            String clickNumbers = String.format("%04d", i).substring(0, 4);
            castAndClick(clickNumbers);
        }
    }


}
